//功能：学子商城服务器程序
//1:下载四个第三方模块
//express           web服务器
//mysql             mysql驱动
//express-session   会话对象
//cors              跨域
//[8080脚手架   4000服务器]
//npm i express mysql express-session cors
//2:引入第三方模块
const express = require("express");
const session = require("express-session");
const mysql = require("mysql");
const cors = require("cors");
//3:创建数据库连接池
var pool = mysql.createPool({
   host:"127.0.0.1",
   user:"root",
   password:"",
   port:3306,
   connectionLimit:15,
   database:"bbbm"  
})
//4:创建web服务器
var server = express();
//5:配置跨域
//允许跨域程序端口
server.use(cors({
    //允许哪个程序列表 脚手架
    origin:["http://127.0.0.1:8080",
    "http://localhost:8080"],
    //每次请求验证
    credentials:true
}));
//6:配置session对象
server.use(session({
   secret:"128位安全字符串",//加密条件
   resave:true,            //请求更新数据
   saveUninitialized:true  //保存初始化数据
}))
//7:指定静态目录  public
server.use(express.static("public")); 
//8:启动监听端口  4000
server.listen(4000);


//功能一;完成用户登录验证
server.get("/login",(req,res)=>{
  //1:获取参数 uname upwd
  var n = req.query.uname;
  var p = req.query.upwd;
  //2:创建sql
  var sql =" SELECT id FROM bbbm_login WHERE uname = ? AND upwd = md5(?)";
  //3:发送sql并且结果返回脚手架
  pool.query(sql,[n,p],(err,result)=>{
     //4:如果发生严重错误抛出
     if(err)throw err;
     //5:登录成功用户名密码有错
     if(result.length==0){
       res.send({code:-1,msg:"用户名或密码有误"})
     }else{
       //6:登录成功
       //?
       res.send({code:1,msg:"登录成功"});
     }
  })
}) 

//测试
//1:启动服务器 node app.js
//2:启动mysql 3006
//3:http://127.0.0.1:4000/login?uname=tom&upwd=122
//3:http://127.0.0.1:4000/login?uname=tom&upwd=123

server.get('/reg',function(req,res){

	//1.获取数据
	var uname=req.query.uname;
	var upwd=req.query.upwd;
	// var email=req.query.email;
	// var phone=req.query.phone;
	var sql1="SELECT * FROM bbbm_login WHERE uname=?";
	pool.query(sql1,[uname],function(err,result){
		if(err)throw err;
		if(result.length>0){
			//查询到结果
			res.send({code:1,msg:'suc'});
		}else{
			var sql2="INSERT INTO bbbm_login VALUES(null,?,?,?)";
			pool.query(sql2,[uname,upwd,phone],function(err,result){
				//console.log(result);
				if(err)throw err;
				if(result.affectedRows>0){
					//注册成功
					res.send({code:200,msg:'reg suc'});
				}else{
					//登录失败
					res.send({code:201,msg:'uname or upwd error'}); 
				}
			})
		}
	})
	
})
	





